package futian
{
	import flash.desktop.NativeApplication;
	import flash.display.Bitmap;
	import flash.display.BitmapData;
	import flash.display.DisplayObject;
	import flash.display.GraphicsPathCommand;
	import flash.display.IGraphicsData;
	import flash.display.Shape;
	import flash.display.Sprite;
	import flash.events.Event;
	import flash.events.IOErrorEvent;
	import flash.events.MouseEvent;
	import flash.events.SecurityErrorEvent;
	import flash.filesystem.File;
	import flash.filters.ColorMatrixFilter;
	import flash.geom.Matrix;
	import flash.geom.Rectangle;
	import flash.net.URLLoader;
	import flash.net.URLLoaderDataFormat;
	import flash.net.URLRequest;
	import flash.net.URLRequestMethod;
	import flash.printing.PrintJob;
	import flash.printing.PrintUIOptions;
	import flash.utils.ByteArray;
	import flash.utils.clearTimeout;
	import flash.utils.setTimeout;

	public class UploadPage extends Sprite
	{
		private static var _main:UploadPage = null;
		public static var photoSprite:Sprite;
		public static function get main():UploadPage
		{
			if(_main==null)
				_main = new UploadPage();
			return _main;
		}

		private var codeBtn:BtnBase;
		private var printBtn:BtnBase;
		private var completeBtn:BtnBase;
		private var backBtn:BtnBase;

		private static var arrloader:ArrLoader;
		private var mylist:MyList = new MyList;

		public function UploadPage()
		{
			_main = this;
			addChild(new Bitmap(test.main.bg.bitmapData));

			var dayinmobanBg:Bitmap;
			dayinmobanBg = new Assets.dayinbg_png;
			dayinmobanBg.x = 1035;
			dayinmobanBg.y = 93;
			addChild(dayinmobanBg);

			codeBtn = new BtnBase(toSend,new Assets.code_png);//("上传");
			printBtn = new BtnBase(toPrint,new Assets.print_png);
			backBtn = new BtnBase(back,new Assets.fanhui_png);
			completeBtn = new BtnBase(complete,new Assets.wancheng_png);
			codeBtn.load(Assets.code_png_url);
			printBtn.load(Assets.print_png_url);
			backBtn.load(Assets.fanhui_png_url);
			completeBtn.load(Assets.wancheng_png_url);

			addChild(printBtn);
			addChild(backBtn);
			addChild(codeBtn);
			addChild(completeBtn);


			completeBtn.x = codeBtn.x = 1089;
			backBtn.x = printBtn.x = 1401;
			printBtn.y = codeBtn.y = 726;
			completeBtn.y = backBtn.y = 885;

			addChild(mylist);
			mylist.x = 1080;
			mylist.y = 186;
			mylist.MaskRect = new Rectangle(0, 0, 670, 450);
			mylist.addEventListener(Event.SELECT, gclicked);
			//mylist.onUpdate = onListUpdate;

			var pathArr:Array = WriteData.getFilePathsInDir("futian/print","\.png$");
			arrloader = new ArrLoader(pathArr,null,oneLoaded); 


			width = test.stageW;
			height = test.stageH;
		}

		private var barBg:Shape = new Shape();
		private var bar:Shape = new Shape();
		private function onListUpdate():void
		{
			var container:Sprite = mylist.container;
			if(container && container.mask && container.height>=container.mask.height){
				var w:int = 15;
				var maskH:int = container.mask.height;
				var mcH:int = container.height;
				var mcY:int = container.y;
				if(mcY>maskH)
					mcY = maskH-1;
				if(mcY<maskH-mcH)
					mcY = maskH-mcH;
				with(barBg.graphics)
				{
					clear();
					beginFill(0xe3e3e3);
					//beginFill(0xffe3e3e3);
					drawRoundRect(0,0,15,maskH,w/2,w/2);
					endFill();
				}
				var yy:int = -mcY /(mcH-maskH)*maskH;
				var hh:int = maskH * (maskH/mcH);
				if(hh+yy>maskH)
					hh = maskH-yy;
				with(bar.graphics)
				{
					clear();
					beginFill(0x939393);
					//beginFill(0x0);
					drawRoundRect(0,yy,15,hh,w/2,w/2);
					endFill();
				}
				mylist.addChild(barBg);
				mylist.addChild(bar);
				barBg.visible = true;
				bar.visible = true;
			}else{
				logs.adds("no bar");
				barBg.visible = false;
				bar.visible = false;
			}
		}

		private function showDefaultPrintBg(e:Event=null):void
		{
			if(arrloader.bmpArr && arrloader.bmpArr.length>0)
			{
				mark(mylist.getItemAt(0) as Sprite);
				changeFrame(0);
			}
		}

		private var curTarget:Sprite;
		private function oneLoaded(e:Event):void
		{
			logs.adds("one loaded");
			var i:int = arrloader.bmpArr.length -1;
			var bmp:Bitmap = arrloader.bmpArr[i] as Bitmap;
			var item:Sprite = new Sprite;
			item.name = ""+i;
			item.mouseChildren = false;
			item.buttonMode = true;
			if(bmp){
				item.addChild(bmp);
			}
			ViewSet.fullCenter(item,int(i%3)*200,int(i/3)*220,180,200);
			mylist.addItem(item);
			if(curTarget==null){
				mark(item);
				changeFrame(i);
			}
		}

		private function gclicked(e:Event):void
		{
			if(bytes)
				return;
			if (e.type == Event.SELECT)
			{
				var target:Sprite = mylist.ClickObject;
				var i:int = int(target.name);
				logs.adds(i);


				if(curTarget!=target){
					mark(target);
					changeFrame(i);
				}
			}
		}

		private function mark(target:Sprite):void
		{
			if(target==null)
				return;
			if(curTargetMask==null){
				curTargetMask = new Sprite;
				with(curTargetMask.graphics)
				{
					clear();
					beginFill(0x0,0.4);
					drawRect(0,0,2,2);
					endFill();
				}
			}

			if(curTarget!=target)
			{
				curTargetMask.width = target.width/target.scaleX;
				curTargetMask.height = target.height/target.scaleY;
				target.addChild(curTargetMask);
				curTarget = target;
			}
		}

		private static var curBgIndex:int = -1;
		private static var bytes:ByteArray;
		private var curTargetMask:Sprite;
		private function changeFrame(i:int):void
		{
			if(curBgIndex==i)
			{
				return;
			}
			curBgIndex = i;
			var bmp:Bitmap;
			var url:String;
			if(arrloader.bmpArr && arrloader.bmpArr.length>i&&i>=0)
			{
				bmp = arrloader.bmpArr[i] as Bitmap;
				url = arrloader.urlArr[i];
			}else{
				return;
			}
			if(bmp==null)
				return;
			if(targetBmp)
			{
				delBmp(targetBmp);
				targetBmp = null;
			}

			if(photoSprite == null)
			{
				photoSprite = new Sprite();
			}
			main.addChild(photoSprite);
			with(photoSprite.graphics)
			{
				//632,900
				//var __matrix:Matrix = new Matrix();
				//__matrix.scale(632/bmp.width,900/bmp.height);
				clear();
				//beginBitmapFill(bitmap:BitmapData, matrix:Matrix = null, repeat:Boolean = true, smooth:Boolean = false)
				beginBitmapFill(bmp.bitmapData,null,false,true);
				//drawRect(0,0,632,900);
				drawRect(0,0,bmp.width,bmp.height);
				endFill();
			}
			//var pos:Array = [45,242,545,366,49,656,537,102,300,90];
			var pos:Array = [156,240,327,274,22,572,391,254,300,90];

			if(url)
			{
				var s:String = url.replace(/^.*[\\\/]([^\\\/]+)$/,"$1");
				var arr:Array = s.match(/[\d]+/g);
				if(arr.length>9)
					pos = arr;
			}
			photoSprite.x = pos[8];
			photoSprite.y = pos[9];
			photoSprite.scaleX = 
				photoSprite.scaleY = 1.0;
			with(photoSprite.graphics)
			{
				beginFill(0xffffff);
				drawRect(pos[0],pos[1],pos[2],pos[3]);
				drawRect(pos[4],pos[5],pos[6],pos[7]);
				endFill();
			}
			ViewSet.fullCenter(photoBmp,pos[0],pos[1],pos[2],pos[3]);
			photoSprite.addChild(photoBmp);

			ViewSet.fullCenter(signBmp,pos[4],pos[5],pos[6],pos[7]);
			photoSprite.addChild(signBmp);

		}

		private var targetBmp:Bitmap;
		private function saveFile():void
		{
			if(bytes){
				bytes.clear();
				bytes = null;
			}
			var bmpd:BitmapData=null;
			if(bmpd){
				bmpd.dispose();
				bmpd = null;
			}
			bmpd = WriteData.displayObject_bitmapDate(photoSprite,false);
			bytes = Jpeg.encode(bmpd);
			targetBmp = new Bitmap(bmpd);
			targetBmp.x = photoSprite.x;
			targetBmp.y = photoSprite.y;
			targetBmp.width = photoSprite.width;
			targetBmp.height = photoSprite.height;
			addChild(targetBmp);
			if(photoSprite.parent)
			{
				photoSprite.parent.removeChild(photoSprite);
			}

			var filename:String = "yonghe/images/"+time2str()+".jpg";
			var photofile:File = WriteData.write_bytes(filename,bytes);
			if(photofile.exists)
				Toast.show("保存成功");

			playPhoto(photofile);
		}
		private static function time2str():String
		{
			var date:Date = new Date;
			return date.getFullYear() + "年" + (date.getMonth()+1) +"月" + date.getDate() +"日" + date.getHours() + "_" + date.getMinutes() +"_" + date.getSeconds();
		}



		private function toPrint():void
		{
			var printSprite:Sprite=null;
			try {
				printSprite = new Sprite;
				var _bgColor:uint = 0xffffff;
				CONFIG::debugging{
					_bgColor = 0xff0000;
				}
				var w:int = Datas.paperWidth;
				var h:int = w*Datas.rate;
				var margin:Number = Datas.margin;
				if(margin<0.01)
					margin=0.01;
				if(margin>1.0)
					margin=1.0;
				trace("printSprite: ",w+"X"+h,margin);
				logs.adds("printSprite: ",w+"X"+h,margin);
				with(printSprite.graphics)
				{
					clear();
					beginFill(_bgColor,1.0);
					drawRect(0,0,w,h);
					endFill();
				}
				logs.adds("printSprite: ");
				CONFIG::debugging{
					stage.addChild(printSprite);
				}
				//var photoObj:Bitmap = new Bitmap(photoObjd);
				var photoObj:Sprite = photoSprite;
				var _x:int = margin*w/2;
				var _y:int = margin*h/2;
				var _w:int = w - _x*2;
				var _h:int = h - _y*2;
				ViewSet.fullCenter(photoObj,_x,_y,_w,_h);
				printSprite.addChild(photoObj);
			}catch(e:Error){
				Toast.show("打印失败");
				return;
			}
			var myPrintJob:PrintJob = new PrintJob();
			var uiOpt:PrintUIOptions = new PrintUIOptions();
			//Toast.show(myPrintJob.pageWidth+"X"+myPrintJob.pageHeight);

			printSprite.height = myPrintJob.pageHeight;
			printSprite.width = myPrintJob.pageWidth;
			uiOpt.minPage = 1;
			uiOpt.maxPage = 1;
			uiOpt.disablePageRange = false;
			var accepted:Boolean = false;
			if(Datas.showPrintDialog)
			{
				accepted = myPrintJob.start();
			}else{
				accepted = myPrintJob.start2(uiOpt,false);
			}
			/*
			   CONFIG::debugging{
			   if (PrintJob.supportsPageSetupDialog)
			   myPrintJob.showPageSetupDialog();
			   }
			 */
			if (accepted)
			{
				try {
					myPrintJob.addPage(printSprite);
					myPrintJob.send();
					Toast.show("打印成功");

					//back();//打印成功后回到上一页
					return;
				} catch (error:Error) {
					Toast.show("打印失败");
				}
			}
			else
			{
				Toast.show("打印失败");
			}
			//打印成功后回到上一页
			CONFIG::debugging{ back(); }
		}

		private static var isUploading:Boolean = false;
		private static var isUploaded:Boolean = false;
		private var savingTimeoutId:uint;
		private function toSend():void
		{
			if(isUploaded)
			{
				showQrCode();
				return;
			}
			if(isUploading)
				return;
			isUploading= true;
			Toast.show("上传中...",0);

			var _url:String = "http://www.zbvision.cn/signature/upload.php";
			CONFIG::debugging { _url = "http://localhost/upload.php"; }
			var req:URLRequest = new URLRequest(_url);
			req.data = bytes;
			req.method = URLRequestMethod.POST;
			req.contentType = "application/octet-stream";

			var loader:URLLoader = new URLLoader();
			loader.dataFormat = URLLoaderDataFormat.BINARY;
			loader.addEventListener(IOErrorEvent.IO_ERROR, uploaded);
			loader.addEventListener(SecurityErrorEvent.SECURITY_ERROR, uploaded);
			loader.addEventListener(Event.COMPLETE, uploaded);
			loader.load(req);
		}


		private function uploaded(e:Event):void
		{
			isUploading = false;
			isUploaded = false;
			Toast.hide();
			CONFIG::debugging{
				//Toast.show("上传成功");
				codeUrl = "testtesttesttesttesttesttesttesttesttesttesttest";
				showQrCode();
				return;
			}

			var remoteUrl:String = null;
			if(e && Event.COMPLETE==e.type){
				var s:String = String(e.target.data);// as String;
				logs.adds(e+"\r\n"+s);
				if(s==null)
				{
					Toast.show(s);
					return;
				}
				var o:Object = null;
				try{
					o = JSON.parse(s);
				}catch(error:Error){
					Toast.show(error.message);
					return;
				}
				if(o==null)
				{
					Toast.show(String(o));
					return;
				}
				if(o.code==1 && o.path!=undefined)
				{
					remoteUrl = "http://www.zbvision.cn/signature/"+o.path;
					//Toast.show("上传成功");
				}else{
					Toast.show(o.msg);
					return;
				}

			}else{
				Toast.show("网络繁忙");
				return;
			}

			logs.adds(remoteUrl);
			codeUrl = remoteUrl;
			showQrCode();
		}

		private static var qrcode:Bitmap;
		private static var qrcodeBg:Bitmap;
		private static var qrcodeContainer:Sprite;
		private static var codeUrl:String;
		private function showQrCode():void
		{
			if(qrcodeContainer==null)
			{
				qrcodeContainer = new Sprite;
				qrcodeBg = new Assets.erweimamingban_png;
				qrcodeContainer.addChild(qrcodeBg);
				ViewSet.center(qrcodeBg,0,0,test.stageW,test.stageH);

				var backbtn:BtnBase = new BtnBase(hideQrCode,new Assets.close_png);
				var backhomebtn:BtnBase = new BtnBase(quit,new Assets.backhome_png);
				backbtn.load(Assets.close_png_url);
				backhomebtn.load(Assets.backhome_png_url);
				qrcodeContainer.addChild(backbtn);
				if(!Datas.willPlayPictures){
					qrcodeContainer.addChild(backhomebtn);
					backbtn.x = qrcodeBg.x + qrcodeBg.width/3-backbtn.width/2;
				}else{
					backbtn.x = qrcodeBg.x + qrcodeBg.width/2-backbtn.width/2;
				}
				backhomebtn.x = qrcodeBg.x + qrcodeBg.width*2/3-backhomebtn.width/2;
				backhomebtn.y = backbtn.y = qrcodeBg.y + qrcodeBg.height*1.1;
				with(qrcodeContainer.graphics)
				{
					clear();
					beginFill(0x0,.4);
					drawRect(0,0,test.stageW,test.stageH);
					endFill();
				}
			}
			qrcodeContainer.visible = true;
			addChild(qrcodeContainer);
			qrcode = QR_Code.str2bmp(codeUrl,200,200,0xff000000,0x0);
			ViewSet.center(qrcode,qrcodeBg.x,qrcodeBg.y-10,qrcodeBg.width,qrcodeBg.height);
			qrcodeContainer.addChild(qrcode);
			isUploaded = true;


		}

		private function quit():void
		{
			NativeApplication.nativeApplication.exit();
		}

		private static function hideQrCode(e:Event=null):void
		{
			if(qrcodeContainer)
				qrcodeContainer.visible = false;
			if(qrcode){
				delBmp(qrcode);
				qrcode = null;
			}
		}

		private static function delBmp(bmp:Bitmap):void
		{
			if(bmp)
			{
				if(bmp.parent)
					bmp.parent.removeChild(bmp);
				bmp.bitmapData.dispose();
			}
		}

		private static var photoBmp:Bitmap;
		private static var signBmp:Bitmap;
		public static function show():void
		{
			isUploading = false;
			isUploaded = false;
			main.curTarget = null;

			if(bytes)
			{
				bytes.clear();
				bytes = null;
			}
			if(photoBmp)
			{
				if(photoBmp.parent)
					photoBmp.parent.removeChild(photoBmp);
				photoBmp = null;
			}
			photoBmp = new Bitmap(SignPage.photoBmp.bitmapData);
			curBgIndex = -1;
			/*
			   var result:Vector.<IGraphicsData> = SignPage.drawBoard.graphics.readGraphicsData(false);
			   with(signBmp.graphics)
			   {
			   clear();
			   drawGraphicsData(result);
			   }
			 */
			if(signBmp)
			{
				if(signBmp.parent)
					signBmp.parent.removeChild(signBmp);
				signBmp = null;
			}
			var signOrigin:DisplayObject = SignPage.drawBoard;
			signBmp = new Bitmap(new BitmapData(signOrigin.width,signOrigin.height,true,0x00000000));
			signBmp.bitmapData.draw(signOrigin);

			main.visible = true;
			test.main.addChild(main);
			main.completeBtn.visible = true;
			main.codeBtn.visible = main.printBtn.visible = false;
			hideQrCode();
			main.showDefaultPrintBg();
		}

		public static function back():void
		{
			//test.quit();
			main.visible = false;
			SignPage.show();
		}

		public function complete():void
		{
			completeBtn.visible = false;
			saveFile();
			codeBtn.visible = printBtn.visible = true;

		}


		public static function playPhoto(photofile:File):void
		{
			//Window2.photoPlayer.show5s(photofile.url);
			Window2.resetPhotoPlayer();
			//Window2.photoPlayer.addPhotoPath(photofile.url,true);
			Window2.photoPlayer.replay();

		}
	}
}
